import store from '@/store';

// 打开页面
export function navigateTo(url) {
	if(url){
		uni.navigateTo({
			url: url
		})
	}else{
		uni.showToast({
			title:'功能开发中，敬请期待',
			icon:'none'
		})
	}
	
}
// 关闭当前 打开新页面
export function redirectTo(url) {
	uni.redirectTo({
		url: url
	})
}
// 关闭所以 打开新页面
export function reLaunch(url) {
	uni.reLaunch({
		url: url
	})
}
// 返回上一页
export function navigateBack(time, num) {
	time = time ? time : 1000;
	num = num ? num : 1;
	return setTimeout(res => {
		uni.navigateBack({
			delta: Number(num)
		})
	}, time);
};
// 获取当前打开过的页面路由
export function getPagePath() {
	let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
	let curRoute = routes[routes.length - 1].route; //获取当前页面路由
	let curParam = routes[routes.length - 1].options; //获取路由参数
	// 拼接参数
	if (Object.getOwnPropertyNames(curParam).length != 0) {
		let param = '';
		for (let key in curParam) {
			param += '&' + key + '=' + curParam[key];
		}
		var path = curRoute + '?' + param.slice(1);
		return uni.setStorageSync('path', '/' + path);
	} else {
		return uni.setStorageSync('path', '/' + curRoute);
	}
}
// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null;
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
	let date;
	if (typeof time === 'object') {
		date = time;
	} else {
		if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
			time = parseInt(time);
		} else if (typeof time === 'string') {
			time = time
				.replace(new RegExp(/-/gm), '/')
				.replace('T', ' ')
				.replace(new RegExp(/\.[\d]{3}/gm), '');
		}
		if (typeof time === 'number' && time.toString().length === 10) {
			time = time * 1000;
		}
		date = new Date(time);
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	};
	return format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key];
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value];
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value;
		}
		return value || 0;
	});
}
// 格式化时间
// this.timestampFormat('2022-07-05 15:10:10'); 
// timestamp:时间戳
// time：2022-07-05 15:10:10'
export const formatDate = (date) => {
	let timestamp = null
	if (typeof date !== 'number') {
		timestamp = Date.parse(date.replace(/-/g, '/')) / 1000 //可解析一个日期时间字符串，并返回 1970/1/1 午夜距离该日期时间的毫秒数。
	} else {
		timestamp = date / 1000
	}

	function zeroize(num) {
		return (String(num).length == 1 ? '0' : '') + num;
	}
	let curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳

	let timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数
	let curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
	let tmDate = new Date(timestamp * 1000); // 参数时间戳转换成的日期对象
	let Y = tmDate.getFullYear(),
		m = tmDate.getMonth() + 1,
		d = tmDate.getDate();
	let H = tmDate.getHours(),
		i = tmDate.getMinutes(),
		s = tmDate.getSeconds();
	if (timestampDiff < 60) { // 一分钟以内
		return "刚刚";
	} else if (timestampDiff < 3600) { // 一小时前之内
		return Math.floor(timestampDiff / 60) + "分钟前";
	} else if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
		if (H <= 12) {
			return '上午' + zeroize(H) + ':' + zeroize(i);
		}
		return '下午' + zeroize(H) + ':' + zeroize(i);
	} else {
		let newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
		if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
			if (H <= 12) {
				return '昨天' + ' ' + '上午' + zeroize(H) + ':' + zeroize(i);
			}
			return '昨天' + ' ' + '下午' + zeroize(H) + ':' + zeroize(i);
		} else if (curDate.getFullYear() == Y) {
			return zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
		} else {
			return Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
		}
	}
}

//大于固定字符串显示省略号
export function handleStr(str, length) {
	let handle_str;
	str.length <= length ? handle_str = str : handle_str = str.slice(0, length) + "...";
	return handle_str
}
//数组对象指定属性过滤
export function arrayObjFilter(arrayObj, keyAttributeArray, keyValue) {
	// 使用列子：
	// let arry = [{
	//  name:"dsa",
	//  key:"152"
	//  },{
	//    name:"ooo",
	//    key:"sdf"
	//  },{
	//    name:123,
	//    key:"wewe"
	//  },{
	//    name:"loe",
	//    key:"uuwe"
	//  }];
	//arrayObjFilter(arry,["name","key"],"12");
	let tmpArray = [];
	for (let i = 0; i < arrayObj.length; i++) {
		for (let j in arrayObj[i]) {
			for (let l = 0; l < keyAttributeArray.length; l++) {
				if (j == keyAttributeArray[l]) {
					if (arrayObj[i][j].toString()
						.indexOf(keyValue) != -1) {
						tmpArray.push(arrayObj[i]);
					}
				}
			}
		}
	}
	return tmpArray;
}
export function deepCopy(obj) {
	let newobj = obj.constructor === Array ? [] : {};
	if (typeof obj !== 'object') {
		return;
	}
	for (let i in obj) {
		newobj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
	}
	return newobj
};
//隐藏部分字符串
export function hideStr(str, frontLen, endLen, zhanweifu = '*') {
	var len = str.length - frontLen - endLen;
	var xing = '';
	for (var i = 0; i < len; i++) {
		xing += zhanweifu;
	}
	return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
}
export function toast(title) {
	uni.showToast({
		icon: 'none',
		title: title
	})
}
export function showConfirm(content) {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title: '温馨提示',
			content: content,
			cancelText: '取消',
			confirmText: '确定',
			success: function(res) {
				resolve(res);
			}
		});
	});
}
export function showActionSheet(content = ['确定', '取消']) {
	return new Promise((resolve, reject) => {
		uni.showActionSheet({
			itemList: content,
			success: function(res) {
				resolve(res)
			},
		});
	})
}
// 根据数据字典 展示枚举内容
export function dictByKey(dict, keys, keycode, keyname) {
	keycode = keycode ? keycode : "value";
	keyname = keyname ? keyname : "label";
	let key = keys;
	if ((key == null || key == "" || key == undefined) && key != 0) {
		return '';
	}

	key = key != 0 ? String(key).split(',') : '0';
	let names = [];
	if (key.length != 0) {
		if (Array.isArray(dict)) {
			dict = treeToArray(dict)
			for (let i = 0; i < dict.length; i++) {
				for (let k = 0; k < key.length; k++) {
					if (dict[i][keycode] == key[k]) {
						names.push(dict[i][keyname]);
					}
				}
			}
		} else {
			for (let i in dict) {
				for (let k = 0; k < key.length; k++) {
					if (i == key[k]) {
						names.push(dict[i]);
					}
				}
			}

		}
		return names.join(',');
	} else if (key == 0) {
		for (let i in dict) {
			if (i == 0) {
				names.push(dict[i][keyname]);
			}
		}
		return names.join(',');
	} else {
		return '';
	}
};

//檢查小程序更新
export function mpUpData() {
	// #ifdef MP-WEIXIN
	//新版本更新
	if (uni.canIUse('getUpdateManager')) {
		//判断当前微信版本是否支持版本更新
		const updateManager = uni.getUpdateManager();
		updateManager.onCheckForUpdate(function(res) {
			if (res.hasUpdate) {
				console.log(res.hasUpdate)
				// 请求完新版本信息的回调
				updateManager.onUpdateReady(function() {
					uni.showModal({
						title: '更新提示',
						content: '新版本已经准备好，将重启应用？',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								// 重启清除本地缓存
								uni.clearStorage();
								updateManager.applyUpdate();
							}
						},
					});
				});
				updateManager.onUpdateFailed(function() {
					uni.showModal({
						// 新的版本下载失败
						title: '已经有新版本了哟~',
						content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
					});
				});
			} else {}
		});
	} else {
		uni.showModal({
			title: '提示',
			content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
		});
	}
	// #endif
}
// 获取系统导航高度
export function systemInfo() {
	uni.getSystemInfo({
		success: (e) => {
			// 获取手机状态栏高度
			let statusBar = e.statusBarHeight
			let customBar
			// #ifndef MP
			customBar = statusBar + (e.platform == 'android' ? 50 : 45)
			// #endif
			// #ifdef MP-WEIXIN
			// 获取胶囊按钮的布局位置信息
			let menu = wx.getMenuButtonBoundingClientRect()
			// 导航栏高度 = 胶囊下距离 + 胶囊上距离 - 状态栏高度
			customBar = menu.bottom + menu.top - statusBar
			// #endif
			// #ifdef MP-ALIPAY
			customBar = statusBar + e.titleBarHeight
			// #endif
			const compensateHeight = 10; //非刘海屏状态栏高度偏低，补充10

			let modelArr = ['X', 'XR', 'XS', '11', '12', '13', '14', '15', '16'];
			let model = e.model;
			model && modelArr.forEach(item => {
				if (model.indexOf(item) != -1 && model.indexOf('iPhone') != -1) {
					e.safeAreaInsetBottom = 20
				}
			})
			e.statusBar = statusBar + compensateHeight
			e.customBar = customBar + compensateHeight
			// #ifdef MP
			e.statusBar = statusBar + compensateHeight + 10
			e.customBar = customBar + compensateHeight + 10
			// #endif
			store.commit('update', ['systemInfo', e])
		}
	})
}


let vibrateShortFn = () => {
	console.log('短震动')
}
// #ifdef APP
if (plus.os.name == 'iOS') {
	vibrateShortFn = () => {
		try {
			var UIImpactFeedbackGenerator = plus.ios.importClass('UIImpactFeedbackGenerator');
			try {
				var impact = new UIImpactFeedbackGenerator();
				impact.prepare();
				impact.init(1);
				impact.impactOccurred();
			} catch (e) {
				//TODO handle the exception
			}
		} catch (e) {
			//TODO handle the exception
		}
	}
} else {
	vibrateShortFn = () => {
		try {
			uni.vibrateShort();
		} catch (e) {
			//TODO handle the exception
		}
	}
}
// #endif
export const vibrateShort = vibrateShortFn


// 节流函数
let timer;
let flag;
export const throttle = (func, wait = 500, immediate = true) => {
	if (immediate) {
		if (!flag) {
			flag = true
			// 如果是立即执行，则在wait毫秒内开始时执行
			typeof func === 'function' && func()
			timer = setTimeout(() => {
				flag = false
			}, wait)
		}
	} else if (!flag) {
		flag = true
		// 如果是非立即执行，则在wait毫秒内的结束处执行
		timer = setTimeout(() => {
			flag = false
			typeof func === 'function' && func()
		}, wait)
	}
}


export const openimg = (index, item, attributes = '') => {
	if (item) {
		// 数组对象请况
		if (attributes) {
			let arr = []
			item.forEach((item, ix) => {
				if (item[attributes]) {
					arr.push(item[attributes])
				}
			})
			uni.previewImage({
				urls: arr,
				current: arr[index]
			});
		} else { // 数组请况
			uni.previewImage({
				urls: item,
				current: item[index]
			});
		}
	} else if (!item) { //传入单张照片
		let arr = []
		arr.push(index)
		uni.previewImage({
			urls: arr,
			current: arr[1]
		});
	}
}

/*
 * 获取定位信息
 */
export function loGetLocation(successCallback) {
	// #ifdef MP-WEIXIN
	uni.authorize({
		scope: 'scope.userLocation',
		success(res) {
			setLocationMap(() => {
				successCallback && successCallback()
			})
		},
		fail(err) {
			store.commit('setLocateInformation', {});
			// 如果用户位置信息没有，则弹出确认框  GPS授权
			uni.showModal({
				content: '请自行在小程序设置中授权位置信息',
				showCancel: false,
				confirmText: '授权',
				success: (res) => {
					if (res.confirm) {
						uni.openSetting({
							success(res) {
								uni.getSetting({
									success(re) {
										if (res.authSetting['scope.userLocation']) {
											setLocationMap(() => {
												successCallback&&successCallback()
											})
										}
									},
									fail(f) {
										store.commit('setLocateInformation', {});
										console.log(f,'====fali loaction')
										uni.showToast({
											title: '请开启手机获取位置功能权限',
											duration: 3000,
											icon: 'none'
										});
									}
								})
	
							}
						})
					}
				}
			})
		}
	});
	// #endif
}
// // 已授权地理位置
export function setLocationMap(callback,fail) {
	uni.getLocation({
		type: 'gcj02',
		success: function(res) {
			store.commit('setLocateInformation', {
				lat: res.latitude,
				lon: res.longitude
			});
			callback && callback(res)
		},
		fail(f) {
			store.commit('setLocateInformation', {});
			fail && fail(f)
			uni.showToast({
				title: '请开启手机获取位置功能权限',
				duration: 3000,
				icon: 'none'
			});
		}
	})
}

/*
 * json数组去重
 * @param: {Array} jsonArr 去重之前的数组
 * @param  {String} field  需要去重的字段值
 */
export function deWeight (jsonArr, field){
	// 数组长度小于2 或 没有指定去重字段 或 不是json格式数据
	if (jsonArr.length < 2 || !field || typeof jsonArr[0] !== "object") return jsonArr;
	let uniqueArr = [jsonArr[0]];
	field = field ? field : 'id';
	for (let i = 1; i < jsonArr.length; i++) {
		let item = jsonArr[i];
		let repeat = false; // 标识位
		for (let j = 0; j < uniqueArr.length; j++) {
			if (item[field] && item[field] == uniqueArr[j][field]) {
				repeat = true;
				break;
			}
		}
		if (!repeat) {
			uniqueArr.push(item);
		}
	}
	return uniqueArr;
}